﻿using Framework.EncryptionService;
using Framework.EncryptionService.Attributes;
using Microsoft.AspNetCore.Http.Features;
using System.Text;

namespace Bright.NetCore.Api.Middleware
{
    /// <summary>
    /// 返回值加密中间件
    /// </summary>
    public class ReturnValueEncryptionMiddleware
    {
        private readonly RequestDelegate _next;

        public ReturnValueEncryptionMiddleware(RequestDelegate requestDelegate)
        {
            _next = requestDelegate;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            var attribute = context.Features.Get<IEndpointFeature>()?.Endpoint?.Metadata?.GetMetadata<NonEncryptedAttribute>();

            var responseBydy = context.Response.Body;
            using (var responseBody = new MemoryStream())
            {
                context.Response.Body = responseBody;
                await _next(context);
                context.Response.Body.Seek(0, SeekOrigin.Begin);
                string responseBodyContent = await new StreamReader(responseBody).ReadToEndAsync();

                //获取返回值加密秘钥
                string str_aesSecret = context.Session.TryGetValue("AesSecret", out _) ? context.Session.GetString("AesSecret") : "";
                // 加密响应内容
                string processedContent = ReturnValueEncryption.ReturnValueEncryptionHelps(responseBodyContent, str_aesSecret, attribute);
                
                // 将流的位置重置为开始
                context.Response.Body.Seek(0, SeekOrigin.Begin);

                // 将处理后的内容写入响应体
                await using (var writer = new StreamWriter(responseBydy))
                {
                    await writer.WriteAsync(processedContent);
                }

            }
        }
    }
}
